import "./HomeConfig.scss";
import React, { Component, Fragment } from "react";
import CustomPreview from "@/components/page/CustomPreview";
import CustomModal from "@/components/common/CustomModal";
import CustomPopconfirm from "@/components/common/CustomPopconfirm";
import CustomQuote from "@/components/common/CustomQuote";
import CustomUpload from "@/components/common/CustomUpload";
import CustomTable from "@/components/common/CustomTable";
import { Switch, Form, Input, InputNumber, Button, message, Select } from "antd";
import HomeSearch from "@/components/page/HomeSearch";
import HomeSwiper from "@/components/page/HomeSwiper";
import HomeIcon from "@/components/page/HomeIcon";
import HomeHotSearch from "@/components/page/HomeHotSearch";
import {
    getAllSwiper,
    addSwiper,
    updateSwiper,
    deleteSwiper,
    getAllIcon,
    addIcon,
    updateIcon,
    deleteIcon,
    getAllHomeConfig,
    addHomeConfig,
    updateHomeConfig,
    getAllPage,
    getAllHotSearch,
    deleteHotSearch,
} from "@/api/page";
import { getAllCommodity } from "@/api/commodity";
const { Option } = Select;
export default class HomeConfig extends Component {
    constructor() {
        super();
        this.state = {
            showSearchChecked: false,
            HtmlJsx: <Fragment></Fragment>,
            tips: "",
            hotSearchColumns: [
                {
                    dataIndex: "keyword",
                    title: "关键词",
                },
                {
                    dataIndex: "time",
                    title: "搜索次数",
                },
                {
                    dataIndex: "operation",
                    title: "操作",
                    render: (text, rowData) => (
                        <CustomPopconfirm
                            title={`确定删除${rowData.keyword}吗？`}
                            onConfirm={() => {
                                deleteHotSearch({ _id: rowData._id }).then(res => {
                                    if (res.code === 200) {
                                        this.CustomHotSearchTable.getDataSource();
                                        message.success("删除成功");
                                    }
                                });
                            }}
                        >
                            {<Button danger>删除</Button>}
                        </CustomPopconfirm>
                    ),
                },
            ],
            hotSearchSourceData: [],
            iconColumns: [
                {
                    dataIndex: "icon",
                    fixed: "left",
                    width: 70,
                    title: "图标",
                    render: text => <Fragment>{<img width="35" src={`${process.env.REACT_APP_FILE}/${text}`} />}</Fragment>,
                },
                {
                    dataIndex: "name",
                    width: 120,
                    title: "名称",
                },
                {
                    dataIndex: "link",
                    width: 240,
                    title: "链接",
                },
                {
                    dataIndex: "pageId",
                    width: 120,
                    title: "页面",
                    render: text => <Fragment>{text && text.pageName ? text.pageName : ""}</Fragment>,
                },
                {
                    dataIndex: "prdId",
                    width: 160,
                    title: "商品",
                    render: text => <Fragment>{text && text.name ? text.name : ""}</Fragment>,
                },
                {
                    dataIndex: "orderIndex",
                    width: 100,
                    title: "排序号",
                },
                {
                    dataIndex: "operation",
                    width: 200,
                    title: "操作",
                    render: (text, rowData) => (
                        <div className="operation-wrap">
                            <Button
                                type="primary"
                                onClick={() => {
                                    this.initIconForm();
                                    const { _id, pageId, prdId } = rowData;
                                    this.setState({ isAddIcon: false, iconModalVisible: true, editIconId: _id }, () => {
                                        let type = null;
                                        if (!pageId && !prdId) {
                                            type = "link";
                                        } else if (prdId) {
                                            type = "prdId";
                                        } else if (pageId) {
                                            type = "pageId";
                                        }
                                        this.setState({ editIconType: type });
                                        this.refs.iconFormRef.setFieldsValue({
                                            ...rowData,
                                            editIconType: type,
                                            pageId: pageId && pageId._id ? pageId._id : "",
                                            prdId: prdId && prdId._id ? prdId._id : "",
                                        });
                                        this.setState({ iconImageUrl: rowData.icon });
                                    });
                                }}
                            >
                                编辑
                            </Button>
                            <CustomPopconfirm
                                title={`确定删除${rowData.name}吗？`}
                                onConfirm={() => {
                                    deleteIcon({ _id: rowData._id }).then(res => {
                                        if (res.code === 200) {
                                            message.success("删除成功");
                                            this.CustomIconTable.getDataSource();
                                        }
                                    });
                                }}
                            >
                                <Button danger>删除</Button>
                            </CustomPopconfirm>
                        </div>
                    ),
                },
            ],
            iconDataSource: [],
            swiperColumns: [
                {
                    dataIndex: "cover",
                    title: "轮播图",
                    width: 160,
                    render(text) {
                        return (
                            <div>
                                <img width="100" src={`${process.env.REACT_APP_FILE}/${text}`} />
                            </div>
                        );
                    },
                },
                {
                    dataIndex: "link",
                    width: 280,
                    title: "链接",
                },
                {
                    dataIndex: "desc",
                    width: 360,
                    title: "描述",
                },
                {
                    dataIndex: "available",
                    title: "是否可用",
                    width: 100,
                    render: (text, rowData) => (
                        <Fragment>
                            {
                                <Switch
                                    checked={text}
                                    checkedChildren="可用"
                                    unCheckedChildren="禁用"
                                    onChange={available => {
                                        updateSwiper({ _id: rowData._id, available }).then(res => {
                                            if (res.code === 200) {
                                                if (available) {
                                                    message.success("已启用");
                                                } else {
                                                    message.success("已禁用");
                                                }
                                                this.CustomSwiperTable.getDataSource();
                                            }
                                        });
                                    }}
                                />
                            }
                        </Fragment>
                    ),
                },
                {
                    title: "操作",
                    width: 200,
                    render: (text, rowData) => {
                        return (
                            <div className="operation-wrap">
                                <Button
                                    type="primary"
                                    onClick={() => {
                                        this.setState({ isAddSwiper: false, swiperModalVisible: true, editSwiperId: rowData._id }, () => {
                                            this.refs.swiperFormRef.setFieldsValue(rowData);
                                            this.setState({ swiperImageUrl: rowData.cover });
                                        });
                                    }}
                                >
                                    编辑
                                </Button>
                                <CustomPopconfirm
                                    title="确定删除这张轮播图吗"
                                    onConfirm={() => {
                                        deleteSwiper({ _id: rowData._id }).then(res => {
                                            if (res.code === 200) {
                                                message.success("删除成功");
                                                this.CustomSwiperTable.getDataSource();
                                            }
                                        });
                                    }}
                                >
                                    <Button danger>删除</Button>
                                </CustomPopconfirm>
                            </div>
                        );
                    },
                },
            ],
            swiperDataSource: [],
            swiperModalVisible: false,
            isAddSwiper: true,
            editSwiperId: null,
            swiperImageUrl: null,
            iconModalVisible: false,
            iconImageUrl: null,
            editIconId: null,
            allPage: [],
            allCommodity: [],
            editIconType: "link",
        };
    }
    UNSAFE_componentWillMount() {
        this.getAllHomeConfig_com();
    }
    getAllHomeConfig_com() {
        getAllHomeConfig().then(res => {
            if (res.code === 200) {
                if (res.data.length == 1) {
                    let record = res.data[0];
                    this.setState({
                        tips: record.tips,
                        showSearchChecked: record.searchVisible,
                        HtmlJsx: (
                            <Fragment>
                                {record.searchVisible ? <HomeSearch tips={record.tips} /> : ""}
                                <HomeHotSearch hotSearches={record.hotSearches} />
                                <HomeIcon icons={record.icons} />
                                <HomeSwiper swipers={record.swipers} />
                            </Fragment>
                        ),
                    });
                }
            }
        });
    }
    initIconForm = async () => {
        let findPageResult = await getAllPage({ pageSize: 999 });
        findPageResult.code == 200 ? this.setState({ allPage: findPageResult.data }) : (allPage = []);
        let findCommodityResult = await getAllCommodity({ pageSize: 999 });
        findCommodityResult.code == 200 ? this.setState({ allCommodity: findCommodityResult.data }) : (allCommodity = []);
    };
    saveHomeConfig = () => {
        const { showSearchChecked, tips, iconDataSource, swiperDataSource, hotSearchDataSource } = this.state;
        return new Promise((resolve, reject) => {
            getAllHomeConfig().then(res1 => {
                if (res1.code === 200) {
                    let homeConfigQuery = {
                        tips,
                        searchVisible: showSearchChecked,
                        hotSearches: hotSearchDataSource.map(item => item._id),
                        icons: iconDataSource.map(item => item._id),
                        swipers: swiperDataSource.map(item => item._id),
                    };
                    if (res1.data.length == 1) {
                        updateHomeConfig({
                            _id: res1.data[0]._id,
                            ...homeConfigQuery,
                        }).then(res2 => {
                            if (res2.code === 200) {
                                resolve();
                            } else {
                                reject(res2.message);
                            }
                        });
                    } else {
                        addHomeConfig(homeConfigQuery).then(res3 => {
                            if (res3.code === 200) {
                                resolve();
                            } else {
                                reject(res3.message);
                            }
                        });
                    }
                } else {
                    reject(res1.message);
                }
            });
        });
    };
    render() {
        const {
            showSearchChecked,
            HtmlJsx,
            tips,
            swiperModalVisible,
            swiperColumns,
            isAddSwiper,
            editSwiperId,
            swiperImageUrl,
            iconColumns,
            iconModalVisible,
            iconImageUrl,
            allPage,
            allCommodity,
            editIconType,
            editIconId,
            isAddIcon,
            hotSearchColumns,
            hotSearchDataSource,
        } = this.state;
        return (
            <>
                <div className="flex HomeConfig">
                    <CustomPreview pageName="首页" HtmlJsx={HtmlJsx} />
                    <div className="rightConfig flex-1 ml-30">
                        <div className="element-warp">
                            <CustomQuote title="搜索" />
                            <Form wrapperCol={{ span: 8 }} labelCol={{ span: 3 }}>
                                <Form.Item label="是否显示搜索" name="show">
                                    <Switch
                                        checkedChildren="显示搜索"
                                        unCheckedChildren="取消搜索"
                                        onChange={e => {
                                            this.setState({ showSearchChecked: e });
                                            if (e) {
                                                this.setState({
                                                    HtmlJsx: (
                                                        <Fragment>
                                                            <HomeSearch tips={tips} />
                                                            <HomeIcon icons={this.state.iconDataSource} />
                                                            <HomeSwiper swipers={this.state.swiperDataSource} />
                                                        </Fragment>
                                                    ),
                                                });
                                            } else {
                                                this.setState({
                                                    HtmlJsx: (
                                                        <Fragment>
                                                            <HomeIcon icons={this.state.iconDataSource} />
                                                            <HomeSwiper swipers={this.state.swiperDataSource} />
                                                        </Fragment>
                                                    ),
                                                });
                                            }
                                        }}
                                        checked={showSearchChecked}
                                    />
                                </Form.Item>
                                {showSearchChecked ? (
                                    <Form.Item label="提示文字" name="tips" initialValue={tips}>
                                        <Input
                                            onChange={e => {
                                                this.setState({ tips: e.target.value });
                                            }}
                                        />
                                    </Form.Item>
                                ) : (
                                    ""
                                )}
                            </Form>
                        </div>
                        <div className="element-warp">
                            <CustomQuote title="热门搜索" />
                            <CustomTable
                                onRef={CustomHotSearchTable => (this.CustomHotSearchTable = CustomHotSearchTable)}
                                format={val => val.sort((a, b) => b.time - a.time)}
                                pagination={{ pageSize: 5 }}
                                columns={hotSearchColumns}
                                api={getAllHotSearch}
                                recDataSource={hotSearchDataSource => this.setState({ hotSearchDataSource })}
                            />
                        </div>
                        <div className="element-warp">
                            <CustomQuote title="图标菜单" />
                            <Button
                                className="mb-10"
                                type="primary"
                                onClick={() => {
                                    this.setState({ iconModalVisible: true, isAddIcon: true, iconImageUrl: "", editIconType: "link" }, () => {
                                        this.refs.iconFormRef.resetFields();
                                    });
                                    this.initIconForm();
                                }}
                            >
                                添加图标菜单
                            </Button>
                            <CustomTable
                                onRef={CustomIconTable => (this.CustomIconTable = CustomIconTable)}
                                format={val => val.sort((a, b) => b.orderIndex - a.orderIndex)}
                                pagination={{ pageSize: 5 }}
                                columns={iconColumns}
                                api={getAllIcon}
                                recDataSource={iconDataSource => this.setState({ iconDataSource })}
                            />
                        </div>
                        <div className="element-warp">
                            <CustomQuote title="轮播图" />
                            <Button
                                className="mb-10"
                                type="primary"
                                onClick={() => {
                                    this.setState({ swiperModalVisible: true, isAddSwiper: true, swiperImageUrl: "" }, () => {
                                        this.refs.swiperFormRef.resetFields();
                                    });
                                }}
                            >
                                添加轮播图
                            </Button>
                            <CustomTable
                                columns={swiperColumns}
                                api={getAllSwiper}
                                pagination={{ pageSize: 3 }}
                                onRef={CustomSwiperTable => (this.CustomSwiperTable = CustomSwiperTable)}
                                recDataSource={swiperDataSource => this.setState({ swiperDataSource })}
                            />
                        </div>
                        <Button
                            size="large"
                            type="primary"
                            className="mt-50"
                            style={{ float: "right" }}
                            onClick={() => {
                                this.saveHomeConfig().then(res => {
                                    this.getAllHomeConfig_com();
                                    message.success("保存成功");
                                });
                            }}
                        >
                            保存
                        </Button>
                    </div>
                </div>

                <CustomModal
                    visible={iconModalVisible}
                    title="添加/编辑图标菜单"
                    onOk={() => {
                        this.refs.iconFormRef.validateFields().then(formData => {
                            if (isAddIcon) {
                                addIcon(formData).then(res => {
                                    if (res.code === 200) {
                                        message.success("添加成功");
                                        this.setState({
                                            iconModalVisible: false,
                                        });
                                        this.CustomIconTable.getDataSource();
                                    }
                                });
                            } else {
                                const { prdId, pageId, link } = formData;
                                let updateData = { ...formData, _id: editIconId };
                                if (prdId) {
                                    updateData = { ...updateData, pageId: null, link: "" };
                                } else if (pageId) {
                                    updateData = { ...updateData, prdId: null, link: "" };
                                } else if (link) {
                                    updateData = { ...updateData, prdId: null, pageId: null };
                                }
                                updateIcon(updateData).then(res => {
                                    if (res.code === 200) {
                                        message.success("修改成功");
                                        this.setState({
                                            iconModalVisible: false,
                                        });
                                        this.CustomIconTable.getDataSource();
                                    }
                                });
                            }
                        });
                    }}
                    onCancel={() => {
                        this.setState({ iconModalVisible: false });
                    }}
                >
                    <Form ref="iconFormRef" wrapperCol={{ span: 12 }} labelCol={{ span: 7 }} initialValues={{ editIconType: "link", orderIndex: 20 }}>
                        <Form.Item label="图标" name="icon" rules={[{ required: true, message: "请上传图标" }]}>
                            <CustomUpload
                                imageUrl={iconImageUrl}
                                onFinish={icon => {
                                    this.refs.iconFormRef.setFieldsValue({ icon });
                                    this.setState({ iconImageUrl: icon });
                                }}
                            />
                        </Form.Item>
                        <Form.Item label="名称" name="name">
                            <Input />
                        </Form.Item>
                        <Form.Item label="排序号(降序)" name="orderIndex">
                            <InputNumber
                                parser={val => {
                                    let value = val.replace(/\$\s?|(\D)|(,*)/g, "");
                                    if (value > 100) {
                                        value = 100;
                                    } else if (value < 0) {
                                        value = 0;
                                    }
                                    return value;
                                }}
                                style={{ width: "100%" }}
                                min={0}
                                max={100}
                            />
                        </Form.Item>
                        <Form.Item label="跳转类型" name="editIconType">
                            <Select onChange={editIconType => this.setState({ editIconType })}>
                                <Option value="link">普通链接</Option>
                                <Option value="prdId">商品</Option>
                                <Option value="pageId">活动页</Option>
                            </Select>
                        </Form.Item>
                        {editIconType == "link" ? (
                            <Form.Item label="链接" name="link">
                                <Input />
                            </Form.Item>
                        ) : editIconType == "prdId" ? (
                            <Form.Item label="商品" name="prdId">
                                <Select>
                                    {allCommodity.map(item => (
                                        <Option key={item._id} value={item._id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        ) : editIconType == "pageId" ? (
                            <Form.Item label="页面" name="pageId">
                                <Select>
                                    {allPage.map(item => (
                                        <Option key={item._id} name="_id">
                                            {item.pageName}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        ) : (
                            ""
                        )}
                    </Form>
                </CustomModal>

                <CustomModal
                    visible={swiperModalVisible}
                    title="添加/编辑轮播图"
                    onOk={() => {
                        this.refs.swiperFormRef.validateFields().then(formData => {
                            if (isAddSwiper) {
                                addSwiper(formData).then(res => {
                                    if (res.code === 200) {
                                        message.success("添加成功");
                                        this.setState({
                                            swiperModalVisible: false,
                                        });
                                        this.CustomSwiperTable.getDataSource();
                                    }
                                });
                            } else {
                                updateSwiper({ ...formData, _id: editSwiperId }).then(res => {
                                    if (res.code === 200) {
                                        message.success("修改成功");
                                        this.setState({
                                            swiperModalVisible: false,
                                        });
                                        this.CustomSwiperTable.getDataSource();
                                    }
                                });
                            }
                        });
                    }}
                    onCancel={() => {
                        this.setState({ swiperModalVisible: false });
                    }}
                >
                    <Form ref="swiperFormRef" wrapperCol={{ span: 12 }} labelCol={{ span: 7 }}>
                        <Form.Item label="轮播图" name="cover" rules={[{ required: true, message: "请上传图片" }]}>
                            <CustomUpload
                                imageUrl={swiperImageUrl}
                                onFinish={cover => {
                                    this.refs.swiperFormRef.setFieldsValue({ cover });
                                    this.setState({ swiperImageUrl: cover });
                                }}
                            />
                        </Form.Item>
                        <Form.Item label="链接" name="link">
                            <Input />
                        </Form.Item>
                        <Form.Item label="描述" name="desc">
                            <Input />
                        </Form.Item>
                    </Form>
                </CustomModal>
            </>
        );
    }
}
